package logic

import (
	"context"
	"errors"
	"hzjt-oam/rpc/sys/internal/config"
	"time"

	"hzjt-oam/rpc/sys/internal/svc"
	"hzjt-oam/rpc/sys/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type MailCodeSendRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMailCodeSendRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MailCodeSendRegisterLogic {
	return &MailCodeSendRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MailCodeSendRegisterLogic) MailCodeSendRegister(in *pb.MailCodeSendRegisterReq) (*pb.MailCodeSendRegisterResp, error) {
	// 该邮箱未被注册
	cnt, err := l.svcCtx.UserModel.FindOneByEmail(l.ctx, in.Email)
	if len(cnt.Name) > 0 {
		err = errors.New("该邮箱已被注册")
		return nil, err
	}
	// 获取验证码
	code := config.RandCode()
	// 存储验证码
	l.svcCtx.RDB.Set(l.ctx, in.Email, code, time.Second*time.Duration(l.svcCtx.Config.Redis.CodeExpire))
	// 发送验证码
	err = config.MailSendCode(
		in.Email,
		cnt.Email,
		l.svcCtx.Config.Email.Subject,
		code,
		l.svcCtx.Config.Email.Username,
		l.svcCtx.Config.Email.Password,
		l.svcCtx.Config.Email.Host,
		l.svcCtx.Config.Email.Post,
	)

	return &pb.MailCodeSendRegisterResp{}, nil
}
